package com.bracelet.config;

import com.bracelet.pojo.entity.CCacheDictionary;
import com.bracelet.pojo.entity.DataDictionaryValue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Component
public class CacheConfig {



    private static List <CCacheDictionary> dictionaryList;
    private static List <DataDictionaryValue> dictionaryValueList;

    CacheConfig(@Value("${spring.datasource.username}")String username,@Value("${spring.datasource.password}")String password,@Value("${spring.datasource.url}")String url) throws  Exception{
        log.info("字典缓存加载...........");
        int loadCache = loadCache(username,password,url);
        log.info("字典缓存加载完成，共计【{}】条数据",loadCache);
    }

    // 加载缓存
    public int loadCache(String username,String password,String url) throws SQLException {
        Connection conn = null;
        ResultSet resultSet = null;
        PreparedStatement prepareStatement = null;
        try {
            // 1、注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2、获取连接
            conn = DriverManager.getConnection(url, username, password);

            // 3、获取预编译SQL语句对象
            prepareStatement = conn.prepareStatement("select * from c_cache_dictionary  ");

            // 4、执行SQL操作，查询操作会返回结果集(相当于一个游标)
            resultSet = prepareStatement.executeQuery();

            // 5、获取结果集
            dictionaryList = new ArrayList<>();
            while (resultSet.next()) {
                CCacheDictionary dictionary = new CCacheDictionary();
                dictionary.setCodeno(resultSet.getString("codeno"));
                dictionary.setCodename(resultSet.getString("codename"));
                dictionary.setItemno(resultSet.getString("itemno"));
                dictionary.setItemname(resultSet.getString("itemname"));
                dictionary.setItemvalue(resultSet.getString("itemvalue"));
                dictionary.setAttributename1(resultSet.getString("attributename1"));
                dictionary.setAttributevalue1(resultSet.getString("attributevalue1"));
                dictionary.setAttributename2(resultSet.getString("attributename2"));
                dictionary.setAttributevalue2(resultSet.getString("attributevalue2"));
                dictionary.setAttributename3(resultSet.getString("attributename3"));
                dictionary.setAttributevalue3(resultSet.getString("attributevalue3"));
                dictionary.setAttributename4(resultSet.getString("attributename4"));
                dictionary.setAttributevalue4(resultSet.getString("attributevalue4"));
                dictionaryList.add(dictionary);
            }


            prepareStatement = conn.prepareStatement("select * from data_dictionary_value  ");

            // 4、执行SQL操作，查询操作会返回结果集(相当于一个游标)
            resultSet = prepareStatement.executeQuery();

            // 5、获取结果集
            dictionaryValueList = new ArrayList<>();
            while (resultSet.next()) {
                DataDictionaryValue dictionary = new DataDictionaryValue();
                dictionary.setValue(resultSet.getString("value"));
                dictionary.setName(resultSet.getString("name"));
                dictionary.setRemark(resultSet.getString("remark"));
                dictionary.setDictionaryCode(resultSet.getString("dictionary_code"));
                dictionaryValueList.add(dictionary);
            }

            // 6、关闭连接，释放资源
            prepareStatement.close();
            conn.close();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (resultSet != null) {
                resultSet.close();
            }
            if (prepareStatement != null && !prepareStatement.isClosed()) {
                prepareStatement.close();
            }
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        }
        return dictionaryList.size();
    }

    // 清除缓存
    public void reloadCache() throws Exception {
        dictionaryList = null;
    }

    /**
     *根据codeno获取指定数据
     */
    public static List<CCacheDictionary> getDictionaryListByCode(String  codeno){
        List<CCacheDictionary> collect = dictionaryList.stream()
                .filter(dictionary -> codeno.equals(dictionary.getCodeno()))
                .collect(Collectors.toList());
        return collect;
    }


    /**
     *  根据codeno+itemno获取全部数据
     * */
    public static CCacheDictionary getDictionaryByItem(String codeno,String itemno){
        CCacheDictionary newdictionary = null;
        Optional<CCacheDictionary> cCacheDictionary = dictionaryList.stream()
                .filter(dictionary -> codeno.equals(dictionary.getCodeno()))
                .filter(dictionary -> itemno.equals(dictionary.getItemno()))
                .findFirst();
        if(cCacheDictionary.isPresent()){
            newdictionary = cCacheDictionary.get();
        }
        return newdictionary;
    }

    /**
     *根据codeno获取指定数据
     */
    public static List<DataDictionaryValue> getDictionaryValueListByCode(String  codeno){
        List<DataDictionaryValue> collect = dictionaryValueList.stream()
                .filter(dictionary -> codeno.equals(dictionary.getDictionaryCode()))
                .collect(Collectors.toList());
        return collect;
    }


    /**
     *  根据codeno+itemno获取全部数据
     * */
    public static DataDictionaryValue getDictionaryValueByItem(String codeno,String itemno){
        DataDictionaryValue newdictionary = null;
        Optional<DataDictionaryValue> cCacheDictionary = dictionaryValueList.stream()
                .filter(dictionary -> codeno.equals(dictionary.getDictionaryCode()))
                .filter(dictionary -> itemno.equals(dictionary.getRemark()))
                .findFirst();
        if(cCacheDictionary.isPresent()){
            newdictionary = cCacheDictionary.get();
        }
        return newdictionary;
    }
}
